/* eslint-disable array-callback-return */
import { message } from 'antd';
import {
  getDetailPricing,
  getListSpeicf,
  getDetailSpeicf,
  submitSpeicf,
  deleteSpeicf,
} from '@/services/productmanage';
import { matchDict } from '@/utils/utils';

export default {
  state: {
    detailInfo: {}, // 产品基本信息
    attrVoList: [], // 属性信息
    pageData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    speicfInfo: {},
  },
  effects: {
    // 详情数据
    *getDetail({ payload }, { call, put }) {
      const response = yield call(getDetailPricing, payload);
      yield put({
        type: 'updateModelData',
        payload: {
          detailInfo: {},
          attrVoList: [],
        },
      });
      if (response.success && response.data) {
        const basicInfo =
          response.data.specifNumVo &&
          response.data.specifNumVo.length &&
          response.data.specifNumVo[0];
        yield put({
          type: 'updateModelData',
          payload: {
            detailInfo: basicInfo,
            attrVoList: response.data.attrVoList || [],
          },
        });
        return response.data;
      }
      return message.warning(response.message || '获取产品定价信息：服务端错误');
    },
    // 获取产品规则查询列表
    *fetchList({ payload }, { call, put }) {
      const response = yield call(getListSpeicf, payload);
      const {
        pageArg: { currentPage, pageSizes },
      } = payload;
      yield put({
        type: 'getList',
        payload: {
          data: [],
          currentPage: 1,
          pageSize: 10,
        },
      });
      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
            currentPage,
            pageSize: pageSizes,
          },
        });
      } else {
        message.warning(`${response.message || '获取产品定价规则信息：服务端错误'}`);
      }
    },
    // 修改获取规则数据
    *getSpeDetail({ payload }, { call, put, select }) {
      const response = yield call(getDetailSpeicf, payload);
      const { attrVoList } = yield select(state => state.speicf);
      if (response.success && response.data) {
        const areaList = [];
        const areaIds = [];
        let suggPrice = 0;

        const { pdPriceList, typePriceMap } = response.data;
        if (pdPriceList && pdPriceList.length) {
          pdPriceList.forEach((item, index) => {
            areaList.push({
              areaId: item.areaCode,
              areaName: item.areaCodeName,
            });
            areaIds.push({
              key: item.areaCode,
              label: item.areaCodeName,
              value: item.areaCode,
            });
            if (!index) {
              const temp = item.suggPrice;
              suggPrice = temp;
            }
          });
          yield put({
            type: 'publicdata/getAreaList',
            payload: areaList,
          });
        }
        if (typePriceMap) {
          Object.entries(typePriceMap).forEach(([key, value]) => {
            attrVoList.forEach((attr, index) => {
              if (attr.attrId === key) {
                attrVoList[index].attrValList = value.split(',');
              }
            });
          });
        }
        yield put({
          type: 'updateModelData',
          payload: {
            speicfInfo: {
              areaIds,
              suggPrice,
              oldSuggPrice: suggPrice,
            },
            attrVoList,
          },
        });
        return response.data;
      }
      return message.warning(response.message || '获取产品定价信息：服务端错误');
    },

    // 提交数据
    *submit(
      {
        payload: { values, pdId, specifId },
      },
      { call, select }
    ) {
      const temps = values;
      const { attrVoList = [] } = yield select(state => state.speicf);
      const { oldSuggPrice = null } = yield select(state => state.speicf.speicfInfo);
      const pdSpecifAttr = [];
      const areaIds = [];
      if (attrVoList.length) {
        Object.entries(values).forEach(([key, value]) => {
          const temp = values;
          attrVoList.forEach(attr => {
            if (attr.attrId === key) {
              pdSpecifAttr.push({
                attrId: key,
                attrVal: value.join(','),
              });
              delete temp[key];
            }
          });
         
        });
      }
      if (values.areaIds && values.areaIds.length) {
        values.areaIds.map(item => {
          areaIds.push(item.value);
        })
        delete temps.areaIds;
      }
      const submitData = specifId
        ? { ...values, pdId, pdSpecifAttr, specifId, oldSuggPrice, areaIds }
        : { ...values, pdId, pdSpecifAttr, areaIds };
      const response = yield call(submitSpeicf, submitData);
      return response;
    },

    // 删除
    *deleteList({ payload }, { call }) {
      const response = yield call(deleteSpeicf, payload);
      return response;
    },
  },
  reducers: {
    // 获取产品定价查询列表
    getList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        pageData: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },
    // 设置修改当前state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 设置页签状态
    updateTabListQuery(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 选择产品
    getProductInfo(
      state,
      {
        payload: { detailInfo, dictCode },
      }
    ) {
      const pdCateName = matchDict(dictCode.PD_CATE, detailInfo.pdCate) || '--';
      const billFreqName = matchDict(dictCode.PD_BILL_FREQ, detailInfo.billFreq) || '--';
      return {
        ...state,
        detailInfo: { ...detailInfo, pdCateName, billFreqName },
      };
    },
  },
};
